import axios from "axios";
import { ElMessage } from "element-plus";
const service = axios.create({
  //process.env.NODE_ENV === 'development' 来判断是否开发环境
  baseURL: globalVar.xiaoliuyubaseURL, //赵元奔8803
  //baseURL: 'http://120.203.64.203:5888', //zwr
  timeout: 120000,
});
//当前ajax请求队列
let pending = [];
let cancelToken = axios.CancelToken;
//清除请求
let removePending = (config) => {
  for (let i in pending) {
    if (pending[i].url === config.url) {
      pending[i].f();
      pending.splice(i, 1);
    }
  }
};
service.interceptors.request.use(
  (config) => {
    removePending(config); //在一个axios发送前执行一下判定操作，在removePending中执行取消操作

    config.cancelToken = new cancelToken(function executor(c) {
      //本次axios请求的配置添加cancelToken
      pending.push({
        url: config.url,
        f: c,
      });
    });
    let token = sessionStorage["token"];
    if (token) {
      config.headers.Authorization = token;
    }

    return config;
  },
  (error) => {
    console.log(error);
    return Promise.reject();
  }
);

service.interceptors.response.use(
  (response) => {
    removePending(response.config);
    switch (response.status) {
      case 200:
        switch (response.data.code) {
          case 1:
            break;
          case 1003:
            ElMessage.error(response.data.message);
            window.location.href = globalVar.tiaozhuanUrl;
            break;
          default:
            let str = response.data.object
              ? response.data.object
              : response.data.message;
            ElMessage.error(str);
            break;
        }
        break;
      default:
        break;
    }
    return response.data;
  },
  (error) => {
    return Promise.reject(error);
  }
);

export default service;
